import type { Component } from 'vue';
import { markRaw } from 'vue';
import { dynamicImport } from '../../hooks/dynamicImport';
import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
import { MODEL_TYPE, getCompositeInfoApi } from '/@/api/config-center/model-design';

const componentMap = {
  BasicModelTable: createAsyncComponent(() => import('/@/components/ModelTable/src/index.vue'), {
    loading: true,
  }),
  ComModelFormPage: createAsyncComponent(
    () => import('/@/components/HComplexPage/components/ComModelFormPage.vue'),
    { loading: true },
  ),
  ComplexPage: createAsyncComponent(() => import('/@/components/HComplexPage/index.vue'), {
    loading: true,
  }),
  ZKRQprojectManagement: createAsyncComponent(
    () => import('/@/views/zkrq/project-management/index.vue'),
    { loading: true },
  ),
};
// Component
export async function useComponent(btnItem): Promise<{
  component: Component;
  isComplex: boolean;
  complexData?: Indexable;
}> {
  let component: Component = componentMap.ComModelFormPage;
  let isComplex = btnItem.componentName === 'ComplexPage';
  let complexData = undefined;
  console.log(
    '%cbtnItem===>32： ',
    'background: rgb(23, 197, 237,.6); color: #ff5023; font-size:18px;font-weight:700',
    btnItem,
    btnItem.parentModel,
  );

  if (btnItem.componentName) {
    let componentFn = componentMap[btnItem.componentName];
    //  默认组件
    if (componentFn) {
      component = componentFn;
    } else {
      // 查询动态组件路径
      componentFn = dynamicImport(btnItem.componentName);
      if (componentFn) {
        component = markRaw(createAsyncComponent(componentFn, { loading: true }));
      }
    }
  } else {
    switch (Number(btnItem.modelClassify)) {
      case MODEL_TYPE.LIST:
        component = componentMap.BasicModelTable;
        break;
      case MODEL_TYPE.FORM:
        component = componentMap.ComModelFormPage;
        break;
      case MODEL_TYPE.COMPLEX:
        isComplex = true;
        component = componentMap.ComplexPage;
        break;
      default:
        break;
    }
    if (isComplex) {
      complexData = await getCompositeData({
        moduleId: btnItem.moduleId,
        modelId: btnItem.dataModelId,
      });
    }
  }

  return { component, isComplex, complexData };
}

async function getCompositeData({ modelId, moduleId }) {
  const data = await getCompositeInfoApi({ modelId, moduleId });

  const ret = data.compositeDesignInfo || {};
  return ret;
}
